package com.cn.customer.housekeeping.housekeepingc.ui;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.customer.housekeeping.housekeepingc.R;
import com.cn.customer.housekeeping.housekeepingc.bean.BaseResp;
import com.cn.customer.housekeeping.housekeepingc.bean.FriendRequestListResp;
import com.cn.customer.housekeeping.housekeepingc.bean.ServicekindListResp;
import com.cn.customer.housekeeping.housekeepingc.bean.ServicekindResp;
import com.cn.customer.housekeeping.housekeepingc.bean.ShopGridviewResp;
import com.cn.customer.housekeeping.housekeepingc.biz.personcenter.IUserLoginView;
import com.cn.customer.housekeeping.housekeepingc.biz.personcenter.InterfacePresenter;
import com.cn.customer.housekeeping.housekeepingc.bridge.BridgeFactory;
import com.cn.customer.housekeeping.housekeepingc.bridge.Bridges;
import com.cn.customer.housekeeping.housekeepingc.bridge.cache.sharePref.EBSharedPrefManager;
import com.cn.customer.housekeeping.housekeepingc.bridge.cache.sharePref.EBSharedPrefUser;
import com.cn.customer.housekeeping.housekeepingc.constant.URLUtil;
import com.cn.customer.housekeeping.housekeepingc.ui.adapter.MyGridViewAdpter;
import com.cn.customer.housekeeping.housekeepingc.ui.adapter.MyGridViewBusinessAdpter;
import com.cn.customer.housekeeping.housekeepingc.ui.adapter.MyViewPagerAdapter;
import com.cn.customer.housekeeping.housekeepingc.ui.adapter.PopShopGridViewAdpter;
import com.cn.customer.housekeeping.housekeepingc.ui.base.BaseActivity;
import com.cn.customer.housekeeping.housekeepingc.ui.base.BaseImgView;
import com.cn.customer.housekeeping.housekeepingc.ui.base.QuickAdapter;
import com.cn.customer.housekeeping.housekeepingc.ui.helper.ItemHelper;
import com.cn.customer.housekeeping.housekeepingc.util.NavUtils;
import com.cn.customer.housekeeping.housekeepingc.util.StringUtil;
import com.cn.customer.housekeeping.housekeepingc.util.ToastUtil;
import com.google.gson.Gson;
import com.lfq.pulltorefresh.library.PullToRefreshBase;
import com.lfq.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;


/***
 *主页==首页
 */
public class HomeListActivity extends BaseActivity implements IUserLoginView {
    private InterfacePresenter mInterfacePresenter;
    private EBSharedPrefManager manager = BridgeFactory.getBridge(Bridges.SHARED_PREFERENCE);
    private QuickAdapter<FriendRequestListResp> mAdapter;
    private ListView mListView;
    private PullToRefreshListView mPullToRefreshListView;
    private int pageNum = 1;
    private int pageSize = 20;
    private TextView tvwu, tv_sudatime;
    private com.cn.customer.housekeeping.housekeepingc.view.MyGridView gv_business;
    private ViewPager viewPager;
    private LinearLayout group;//圆点指示器
    private ImageView[] ivPoints;//小圆点图片的集合
    private int totalPage; //总的页数
    private int mPageSize = 8; //每页显示的最大的数量
    //    private List<ProdctBean> listDatasClassifyA, listDatasClassifyB, listDatasClassifyC;//总的数据源
    private List<View> viewPagerList;//GridView作为一个View对象添加到ViewPager集合中
    private ImageView iv_guanggao;
    private Button wangdaileiBtn, baobaoleiBtn;
    private ServicekindResp mServicekindResp;
    private RelativeLayout rl_suda;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main_list);
        super.onCreate(savedInstanceState);
    }


    @Override
    public void initViews() {
        mInterfacePresenter = new InterfacePresenter();
        mInterfacePresenter.attachView(this);
        mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
        tvwu = (TextView) findViewById(R.id.tvwu);
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
        mListView = mPullToRefreshListView.getRefreshableView();
        mListView.setHeaderDividersEnabled(false);
        mListView.setDividerHeight(0);

        LayoutInflater lif = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View headerView = lif.inflate(R.layout.listview_headview_home_gridview, null);
        wangdaileiBtn = (Button) headerView.findViewById(R.id.wangdaileiBtn);
        baobaoleiBtn = (Button) headerView.findViewById(R.id.baobaoleiBtn);
        viewPager = (ViewPager) headerView.findViewById(R.id.viewpager);
        group = (LinearLayout) headerView.findViewById(R.id.points);
        iv_guanggao = (ImageView) headerView.findViewById(R.id.iv_guanggao);
        tv_sudatime = (TextView) headerView.findViewById(R.id.tv_sudatime);
        rl_suda = (RelativeLayout) headerView.findViewById(R.id.rl_suda);
        gv_business = (com.cn.customer.housekeeping.housekeepingc.view.MyGridView) headerView.findViewById(R.id.gv_business);


        BaseImgView.ImageLoaderLoadimg(iv_guanggao,
                "http://img0.imgtn.bdimg.com/it/u=771723016,2236022390&fm=27&gp=0.jpg", R.mipmap.icon_fang, R.mipmap.icon_fang, R.mipmap.icon_fang, 60, 60, 20);
        mListView.addHeaderView(headerView);
    }


    @Override
    public void initListeners() {
        wangdaileiBtn.setOnClickListener(this);
        baobaoleiBtn.setOnClickListener(this);
        iv_guanggao.setOnClickListener(this);


        //速达
        gv_business.setOnItemClickListener(new gridViewListener());


        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageNum = 1;

//                mInterfacePresenter.getBlacklist(pageNum, pageSize);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//                mInterfacePresenter.getBlacklist(pageNum, pageSize);
            }
        });

        mPullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int headerCount = mListView.getHeaderViewsCount();
                if (position >= headerCount) {
//                    FriendRequestListResp item = mAdapter.getItem(position - headerCount);
//                    UserInfo   userInfo = new UserInfo(item.getUid(), item.getNickname(), Uri.parse(item.getHeadpic()));
//                    if (userInfo != null) {
//                        Friend friend = CharacterParser.getInstance().generateFriendFromUserInfo(userInfo);
//                        NavUtils.gotoAddUserDataActivity(BlackActivity.this, friend);
//                    }
                }
            }
        });

    }

    class gridViewListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            Object obj = gv_business.getItemAtPosition(arg2);
            if (obj != null) {
                NavUtils.gotoOrderFragmentListActivity(HomeListActivity.this, ((ServicekindListResp) obj).getType(), cityname, ((ServicekindListResp) obj).getName());
            }

        }
    }

    String cityname = "";

    @Override
    public void initData() {
        ItemHelper mItemHelper = new ItemHelper();
        mAdapter = mItemHelper.setAdapterHomeList(this, new ArrayList());
        mListView.setAdapter(mAdapter);

        List<FriendRequestListResp> listA = new ArrayList();
        listA.add(new FriendRequestListResp());
        listA.add(new FriendRequestListResp());
        listA.add(new FriendRequestListResp());
        listA.add(new FriendRequestListResp());
        listA.add(new FriendRequestListResp());
        mAdapter.replaceAll(listA);


        String city = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.city, "");
        String cityChoice = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.cityChoice, "");

        if (!StringUtil.isEmpty(cityChoice)) {
            cityname = cityChoice;
        } else if (!StringUtil.isEmpty(city)) {
            cityname = city;
        } else {
        }

        mInterfacePresenter.getServicekind(manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lat, ""), manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lon, ""), cityname);
    }

    @Override
    public void setHeader() {
        super.setHeader();
        rlTitle.setVisibility(View.GONE);

    }

    public void popFenlei() {
        View popupView = getLayoutInflater().inflate(R.layout.pop_shoporderlist_menu, null);
        GridView mineMainview = (GridView) popupView.findViewById(R.id.mineMainview);

        List<ShopGridviewResp> lists = new ArrayList<ShopGridviewResp>();
        ShopGridviewResp m=new ShopGridviewResp();
        m.setTitle("全部分类1");
        lists.add(m);

        ShopGridviewResp m2=new ShopGridviewResp();
        m2.setTitle("全部分类2");
        lists.add(m2);

        ShopGridviewResp m3=new ShopGridviewResp();
        m3.setTitle("全部分类3");
        lists.add(m3);

        ShopGridviewResp m4=new ShopGridviewResp();
        m4.setTitle("全部分类4");
        lists.add(m4);



      final   PopShopGridViewAdpter pictureAdapter = new PopShopGridViewAdpter(this, lists);
        mineMainview.setAdapter(pictureAdapter);



        mineMainview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int select,
                                    long arg3) {
                pictureAdapter.changeStatus(select);//设置选中项
                pictureAdapter.notifyDataSetChanged();//更新列表
            }
        });








        PopupWindow window = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        window.setAnimationStyle(R.style.popup_window_anim);
        window.setTouchable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(0.5f);
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        window.update();
        window.showAsDropDown(wangdaileiBtn, 0, 0);
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.wangdaileiBtn://猜你喜欢
                popFenlei();

                wangdaileiBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.switch_button_left_checked));
                baobaoleiBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.switch_button_right));

                List<FriendRequestListResp> listA = new ArrayList();
                listA.add(new FriendRequestListResp());
                listA.add(new FriendRequestListResp());
                listA.add(new FriendRequestListResp());
                listA.add(new FriendRequestListResp());
                listA.add(new FriendRequestListResp());
                mAdapter.replaceAll(listA);


                break;
            case R.id.baobaoleiBtn://热门推荐

                wangdaileiBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.switch_button_left));
                baobaoleiBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.switch_button_right_checked));
                List<FriendRequestListResp> listB = new ArrayList();
                listB.add(new FriendRequestListResp());
                listB.add(new FriendRequestListResp());
                listB.add(new FriendRequestListResp());
                mAdapter.replaceAll(listB);
                break;
            case R.id.iv_guanggao://中间图片


                break;

        }


        super.onClick(v);
    }

    @Override
    public void onError(BaseResp s) {
        mPullToRefreshListView.onRefreshComplete();
    }


    @Override
    public void onSuccess(BaseResp s) {
        mPullToRefreshListView.onRefreshComplete();
        if (s.getUrl().equals(URLUtil.url_get_servicekind)) {//首页服务类型
            Gson gson = new Gson();
            mServicekindResp = gson.fromJson(s.getData(), ServicekindResp.class);
            if (mServicekindResp != null) {
                setTopMenu(mServicekindResp);
            } else {
                viewPager.setVisibility(View.GONE);
                rl_suda.setVisibility(View.GONE);
                gv_business.setVisibility(View.GONE);
            }


        } else {
            ToastUtil.makeText(HomeListActivity.this, s.getMessage());
        }
    }

    public void setTopMenu(ServicekindResp mServicekindResp) {
//顶部菜单
        if (mServicekindResp.getMenuList() != null && mServicekindResp.getMenuList().size() > 0) {

            viewPager.setVisibility(View.VISIBLE);
            totalPage = (int) Math.ceil(mServicekindResp.getMenuList().size() * 1.0 / mPageSize);
            viewPagerList = new ArrayList<View>();
            for (int i = 0; i < totalPage; i++) {
                //每个页面都是inflate出一个新实例
                final GridView gridView = (GridView) View.inflate(this, R.layout.item_gridview, null);
                gridView.setAdapter(new MyGridViewAdpter(this, mServicekindResp.getMenuList(), i, mPageSize));
                //添加item点击监听
                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int position, long arg3) {
                        // TODO Auto-generated method stub
                        Object obj = gridView.getItemAtPosition(position);
                        if (((ServicekindListResp) obj).getType().equals("2000")) {
                            NavUtils.gotoClassifyActivity(HomeListActivity.this);
                        } else {
                            NavUtils.gotoOrderFragmentListActivity(HomeListActivity.this, ((ServicekindListResp) obj).getType(), cityname, ((ServicekindListResp) obj).getName());

                        }
                    }
                });
                //每一个GridView作为一个View对象添加到ViewPager集合中
                viewPagerList.add(gridView);
            }
            //设置ViewPager适配器
            viewPager.setAdapter(new MyViewPagerAdapter(viewPagerList));

            //添加小圆点
            ivPoints = new ImageView[totalPage];
            for (int i = 0; i < totalPage; i++) {
                //循坏加入点点图片组
                ivPoints[i] = new ImageView(this);
                if (i == 0) {
                    ivPoints[i].setImageResource(R.mipmap.index_category_indicator_selected);
                } else {
                    ivPoints[i].setImageResource(R.mipmap.index_category_indicator_nor);
                }
                ivPoints[i].setPadding(8, 8, 8, 8);
                group.addView(ivPoints[i]);
            }
            //设置ViewPager的滑动监听，主要是设置点点的背景颜色的改变
            viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // TODO Auto-generated method stub
                    //currentPage = position;
                    for (int i = 0; i < totalPage; i++) {
                        if (i == position) {
                            ivPoints[i].setImageResource(R.mipmap.index_category_indicator_selected);
                        } else {
                            ivPoints[i].setImageResource(R.mipmap.index_category_indicator_nor);
                        }
                    }
                }
            });

        } else {
            viewPager.setVisibility(View.GONE);
        }
        //速达菜单
        if (mServicekindResp.getSuDaList() != null && mServicekindResp.getSuDaList().size() > 0) {
//            rl_suda.setVisibility(View.VISIBLE);
            gv_business.setVisibility(View.VISIBLE);
            tv_sudatime.setText(mServicekindResp.getDesc());
            gv_business.setAdapter(new MyGridViewBusinessAdpter(this, mServicekindResp.getSuDaList()));
        } else {
            rl_suda.setVisibility(View.GONE);
            gv_business.setVisibility(View.GONE);
        }
    }

    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
